//
//  AppDelegate.h
//  Address-book📞
//
//  Created by Mars_ZXB on 16/8/6.
//  Copyright © 2016年 BAT3. All rights reserved.
//


#import "VC1stOfContact.h"
#import "VC2ndOfContact.h"
#import "VC3rdOfContactDetail.h"
#import "CellOfContact.h"
#import "TableViewOfContact.h"
#import "HandleImage.h"
#import "DataBaseHandleContact.h"
#import "ModelOfContact.h"


static NSString *pool1 = @"pool1";

@interface VC1stOfContact () <UITableViewDataSource, UITableViewDelegate, VC2ndOfContactDelegate>

@property (nonatomic, retain) TableViewOfContact *tableView;

@property (nonatomic, retain) NSMutableArray *arrOfSectionKeys;

@property (nonatomic, retain) NSMutableDictionary *dicOfContact;

@end

@implementation VC1stOfContact

- (void)viewDidLoad {
    [super viewDidLoad];
    //主题
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"3a2e186c8a6444b988c4b8cd3e0b9f78"]];
    self.dicOfContact = [NSMutableDictionary dictionary];
    NSLog(@"%@", NSHomeDirectory());
    [[DataBaseHandleContact sharaDateBaseHandleContact] openSQLName:@"DLS160710.sqlite"];
   //导入数据
//   [[DataBaseHandleContact sharaDateBaseHandleContact] createTabel];
//    [self inputPlist];
    
    [self handleData];
    [self configNavi];
    [self createTableView];

    // Do any additional setup after loading the view.


}

#pragma mark - 处理数据
/** 处理数据 */
- (void)handleData {
    // 重新开辟空间.
    [self.dicOfContact removeAllObjects];

    NSMutableArray *arr = [[DataBaseHandleContact sharaDateBaseHandleContact] select].mutableCopy;
 
    for (ModelOfContact *model in arr) {
        if ([self.dicOfContact objectForKey:model.section] == nil) {
            NSMutableArray *arrOfSection = [NSMutableArray array];
            [self.dicOfContact setObject:arrOfSection forKey:model.section];
        }
        [HandleImage loadImage:model];
        [[self.dicOfContact objectForKey:model.section] addObject:model];
    }
    
    self.arrOfSectionKeys = [[self.dicOfContact allKeys] sortedArrayUsingSelector:@selector(compare:)].mutableCopy;



}
/** 导入文件 */
- (void)inputPlist{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"DLS160710" ofType:@"plist"];
    NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:path];
    for (NSString *key in dictionary) {
        NSMutableArray *arr = [dictionary objectForKey:key];
        for (NSMutableDictionary *smallDic in arr) {
            ModelOfContact *model = [[ModelOfContact alloc] init];
            [model setValuesForKeysWithDictionary:smallDic];
            [[DataBaseHandleContact sharaDateBaseHandleContact]insertModel:model WithSection:[model.name substringToIndex:1].uppercaseString];
        }
    }
   
}

#pragma mark - 配置.

- (void)configNavi {
    self.navigationItem.title = @"通讯录";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(handleAdd:)];
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
/** 跳转添加联系人界面 */
- (void)handleAdd:(UIBarButtonItem *)button {
    VC2ndOfContact *second = [[VC2ndOfContact alloc]init];
    second.delegate = self;
    [self.navigationController pushViewController:second animated:YES];


}
/** 进入编辑状态. */
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];

}

#pragma mark - 添加联系人协议方法.
/** 协议方法, 添加联系人. */
- (void)addContact:(ModelOfContact *)model {
    [[DataBaseHandleContact sharaDateBaseHandleContact] insertModel:model WithSection:model.section];
    [HandleImage saveImageWith:model];
    [self handleData];
    
    [self.tableView reloadData];
    

}



#pragma mark - 创建 tableView 
- (void)createTableView {
    self.tableView = [[TableViewOfContact alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"3a2e186c8a6444b988c4b8cd3e0b9f78"]];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[CellOfContact class] forCellReuseIdentifier:pool1];
    [self.view addSubview:self.tableView];
}

#pragma mark - tableDataSource
/** row number */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *key = [self.arrOfSectionKeys objectAtIndex:section];
    NSMutableArray *array = [self.dicOfContact objectForKey:key];
    return array.count;

}

/** section number */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.arrOfSectionKeys.count;
}

/** section header title */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self.arrOfSectionKeys objectAtIndex:section];
}

/** 配置 Cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CellOfContact *cell = [tableView dequeueReusableCellWithIdentifier:pool1];
    cell.alpha = 1;
    ModelOfContact *model = [[self.dicOfContact objectForKey:[self.arrOfSectionKeys objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    // 赋值
    [cell setContentValueWithModel:model];
    // 点击事件
    [cell addTarget:self action:@selector(pushDetail:)];
    
    return cell;


}

/** 右侧索引栏 */
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.arrOfSectionKeys;
}

/** 提交编辑命令 */
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CellOfContact *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    NSString *sectionTitle = [self.arrOfSectionKeys objectAtIndex:indexPath.section];
    // 删除本地数据
    [[DataBaseHandleContact sharaDateBaseHandleContact]deleteModel:cell.modelOfCell];
    // 刷新缓存数据.
    [self handleData];
    // 判断数据中该分区是否存在.
    if ([self.arrOfSectionKeys containsObject:sectionTitle]) {
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    // 如果不存在, 直接删除分区.
    else {
    NSIndexSet *indexset = [NSIndexSet indexSetWithIndex:indexPath.section];
    [tableView deleteSections:indexset withRowAnimation:UITableViewRowAnimationAutomatic];
    }

}

#pragma mark - Cell 点击事件.
- (void)pushDetail:(CellOfContact *)cell {
    
    VC3rdOfContactDetail *third = [[VC3rdOfContactDetail alloc]init];
    third.modelOfDetail = cell.modelOfCell;
    [self.navigationController pushViewController:third animated:YES];
    
}

#pragma mark - delegate
/** 设置行高 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;
}

/** 设置编辑风格 */
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end
